#include "../include/client.h"

int sendFile(int sockfd,char *buf,char *fileRealName,int flag){
    train_t train;
    char filename[4096] = {0};
    memcpy(filename,buf,strlen(buf));
    int filefd = open(filename,O_RDONLY);
    if(filefd == -1){
        train.flag = -1;
        train.length = strlen(filename);
        memcpy(train.data,filename,train.length);
        send(sockfd,&train,sizeof(train.flag)+sizeof(train.length)+train.length,MSG_NOSIGNAL);
        printf("打开文件失败!\n");
        return -1;
    }
    train.flag = flag;
    train.length = strlen(filename);
    memcpy(train.data,filename,train.length);
    send(sockfd,&train,sizeof(train.flag)+sizeof(train.length)+train.length,MSG_NOSIGNAL);
    train.length = strlen(fileRealName);
    memcpy(train.data,fileRealName,train.length);
    send(sockfd,&train,sizeof(train.flag)+sizeof(train.length)+train.length,MSG_NOSIGNAL);
    struct stat statbuf;
    fstat(filefd,&statbuf);
    off_t filesize=statbuf.st_size;
    train.length=sizeof(off_t);
    memcpy(train.data,&filesize,sizeof(off_t));
    printf("size = %ld\n",filesize);
    send(sockfd,&train,sizeof(train.flag)+sizeof(train.length)+train.length,MSG_NOSIGNAL);
    while(1){
        bzero(train.data,sizeof(train.data));
        ssize_t ret=read(filefd,train.data,sizeof(train.data));
        train.length=ret;//记录实际读取的字节数
        send(sockfd,&train,sizeof(train.flag)+sizeof(train.length)+train.length,MSG_NOSIGNAL);
        if(ret==0){//读取完毕，退出循环
            break;
        }
    }
    close(filefd);
    return 0;
}
